using AutoMapper;
using MediatR;
using RBAC.Domain.SmartHealthcare.Hosiptial;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using SmartHealthcare.Read.Api.Application.Command.Payment;
using SmartHealthcare.Read.Api.DTo;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace SmartHealthcare.Read.Api.Application.Handler.Payment
{
    /// <summary>
    /// 获取支付记录列表处理器
    /// </summary>
    public class GetPaymentRecordsHandler : IRequestHandler<GetPaymentRecordsCommand, APIResult<List<PaymentRecordDto>>>
    {
        private readonly IBaseRepository<PaymentRecordModel> paymentRepository;
        private readonly IMapper mapper;
        private readonly ILogger<GetPaymentRecordsHandler> logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="paymentRepository">支付记录仓储</param>
        /// <param name="mapper">对象映射器</param>
        /// <param name="logger">日志记录器</param>
        public GetPaymentRecordsHandler(
            IBaseRepository<PaymentRecordModel> paymentRepository,
            IMapper mapper,
            ILogger<GetPaymentRecordsHandler> logger)
        {
            this.paymentRepository = paymentRepository;
            this.mapper = mapper;
            this.logger = logger;
        }

        /// <summary>
        /// 处理获取支付记录列表请求
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>支付记录列表</returns>
        public Task<APIResult<List<PaymentRecordDto>>> Handle(GetPaymentRecordsCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<PaymentRecordDto>> result = new APIResult<List<PaymentRecordDto>>();

            try
            {
                logger.LogInformation($"开始查询支付记录，查询条件：InpatientRegistryId={request.InpatientRegistryId}, " +
                    $"MedicalCard={request.MedicalCard}, PatientName={request.PatientName}, " +
                    $"StartTime={request.StartTime}, EndTime={request.EndTime}, " +
                    $"PaymentMethod={request.PaymentMethod}, PaymentType={request.PaymentType}");

                // 获取所有未删除的支付记录
                var query = paymentRepository.GetALL().Where(x => x.IsDeleted == false);

                // 根据住院登记ID筛选
                if (request.InpatientRegistryId.HasValue)
                {
                    query = query.Where(x => x.InpatientRegistryId == request.InpatientRegistryId.Value);
                    logger.LogInformation($"添加住院登记ID筛选条件：{request.InpatientRegistryId.Value}");
                }

                // 根据病人卡号筛选
                if (!string.IsNullOrEmpty(request.MedicalCard))
                {
                    query = query.Where(x => x.MedicalCard == request.MedicalCard);
                    logger.LogInformation($"添加病人卡号筛选条件：{request.MedicalCard}");
                }

                // 根据患者姓名筛选
                if (!string.IsNullOrEmpty(request.PatientName))
                {
                    query = query.Where(x => x.PatientName.Contains(request.PatientName));
                    logger.LogInformation($"添加患者姓名筛选条件：{request.PatientName}");
                }

                // 根据时间范围筛选
                if (request.StartTime.HasValue)
                {
                    query = query.Where(x => x.PaymentTime >= request.StartTime.Value);
                    logger.LogInformation($"添加开始时间筛选条件：{request.StartTime.Value}");
                }

                if (request.EndTime.HasValue)
                {
                    query = query.Where(x => x.PaymentTime <= request.EndTime.Value);
                    logger.LogInformation($"添加结束时间筛选条件：{request.EndTime.Value}");
                }

                // 根据支付方式筛选
                if (!string.IsNullOrEmpty(request.PaymentMethod))
                {
                    query = query.Where(x => x.PaymentMethod == request.PaymentMethod);
                    logger.LogInformation($"添加支付方式筛选条件：{request.PaymentMethod}");
                }

                // 根据支付类型筛选
                if (!string.IsNullOrEmpty(request.PaymentType))
                {
                    query = query.Where(x => x.PaymentType == request.PaymentType);
                    logger.LogInformation($"添加支付类型筛选条件：{request.PaymentType}");
                }

                // 按支付时间降序排序（最新的记录在前）
                query = query.OrderByDescending(x => x.PaymentTime);

                // 执行查询并转换为DTO
                var records = query.ToList();
                var recordDtos = mapper.Map<List<PaymentRecordDto>>(records);

                logger.LogInformation($"查询结果：共找到{recordDtos.Count}条支付记录");

                result.Data = recordDtos;
                result.Code = APIEnums.Success;
                result.Msg = "查询支付记录成功";
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "查询支付记录时发生异常");
                result.Code = APIEnums.Error;
                result.Msg = $"查询支付记录失败：{ex.Message}";
            }

            return Task.FromResult(result);
        }
    }
} 